package cn.tedu._04weibo.base.exception;


import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * ControllerAdvice注解:
 * 1.标识该类为全局异常处理器的类;
 * 2.当抛出异常时,Spring MVC会检查是否有对应的全局异常处理器的类;
 * <p>
 * RestControllerAdvice注解:
 * 1.组合注解: @ControllerAdvice + @ResponseBody;
 */
//@ControllerAdvice
//@ResponseBody
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException exception) {
        //exception.getMessage():获取异常提示消息
        String data = exception.getMessage();
        log.error("IllegalArgumentException:" + data);
        //{"state":3000,"message":操作失败,"data":车辆id不能小于0}
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    /**
     * Validation封装类参数数据合法性校验的异常处理方法
     * @param exception
     * @return
     */
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        String data=exception.getMessage();
        log.error("MethodArgumentNotValidException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandlerRunTimeException(RuntimeException exception) {
        String data = exception.getMessage();
        log.error("RuntimeException:" + data);
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }
//    @ExceptionHandler
//    public JsonResult doHandlerThrowable(Throwable exception){
//        String data = exception.getMessage();
//        log.error("未知异常:" + data);
//        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
//    }
}
